package xin.petstore.framework.web.img.dbmanager;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import com.eloancn.common.img.domain.CodeImage;
import com.mongodb.gridfs.GridFSDBFile;

@Repository("imgCodeRepositoryDao")
public class ImgCodeRepositoryDao extends BaseMgRepository<CodeImage> {
	
	public ImgCodeRepositoryDao() {
		super.setFileName("imgcode");
	}

	@Override
	public List<GridFSDBFile> getGridFSList(List<String> dbObject) {
		List<GridFSDBFile> list = new ArrayList<GridFSDBFile>();
		for (int i = 0; i < dbObject.size(); i++) {
			Query query = new Query();
			Criteria criteria = Criteria.where("category").is(dbObject.get(i));  
			query.addCriteria(criteria);
			Long count = super.getMongoTemplate().count(query, CodeImage.class);
			query.skip(random.nextInt(count.intValue()));
			CodeImage one = super.getMongoTemplate().find(query, CodeImage.class).get(0);
			GridFSDBFile file = super.getGridFS().find( ObjectId.massageToObjectId(one.getOriginalId()));
			list.add(file);
		}
		return list;
	}
	private static final Random random = new Random();
}
